/* vim: set expandtab tabstop=4 softtabstop=4 shiftwidth=4: */
/* Copyright (C) 2012 Zongyou Yao. All rights reserved.     */

#include <string.h>
#include <limits.h>
#include "assert.h"
#include "fmt.h"
#include "str.h"
#include "mem.h"

#define idx(i, len) ((i) <= 0 ? (i) + (len) : (i) - 1)
#define convert(s, i, j)             \
do { \
    int len;                  \
    assert(s);                \
    len = strlen(s);          \
    i = idx(i, len);          \
    j = idx(j, len);          \
    if (i > j) {              \
        int t = i; i = j; j = t; \
    }    \
    assert(i >= 0 && j <= len);   \
} while(0)

char *str_sub(const char *s, int i, int j)
{
    char *str, *p;
    convert(s, i, j);
    p = str = ALLOC(j - i + 1);
    while (i < j) {
        *p++ = s[i++];
    }
    *p = '\0';
    return str;
}
